package org.wheel.plugins.starter.jdbc.pool.config;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.beans.factory.FactoryBean;
import org.wheel.plugins.starter.autoconfigure.DynamicDataSourceProperties;

import java.lang.reflect.Proxy;

public class DaoFactory<T> implements FactoryBean<T> {

    // 直接使用 LogFactory 创建日志对象，Hutool 会自动检测项目中的日志框架（优先级：Slf4j > Log4j > Logback > JDK Logging）
    private static final Log log = LogFactory.get();

    // 定义的接口类
    private final Class<T> daoInterface;

    private final DynamicDataSourceProperties conn;

    private final DaoConfigProperties daoConfigProperties;

    public DaoFactory(Class<T> daoInterface, DynamicDataSourceProperties conn, DaoConfigProperties daoConfigProperties) {
        log.trace("DaoFactory: " + daoInterface.getName());
        this.daoInterface = daoInterface;
        this.conn = conn;
        this.daoConfigProperties = daoConfigProperties;
    }

    @Override
    public T getObject() throws Exception {
        T proxy = (T) Proxy.newProxyInstance(
                daoInterface.getClassLoader(),
                new Class[]{daoInterface},
                new DaoProxy(daoInterface, conn, daoConfigProperties));
        log.trace("Generated proxy for: " + daoInterface.getName());
        return proxy;
    }


    @Override
    public Class<?> getObjectType() {
        return daoInterface;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}